package com.boodaba.todocarts.infstr;

import java.util.List;

public class Db4oStoreContext implements IStoreContext {
	private Db4oContainerHolder mContainerHolder;
			
	public Db4oStoreContext(String dbFilePath) {
		mContainerHolder = new Db4oContainerHolder(dbFilePath);
	}
	
	@Override
	public <T> List<T> allOf(Class<T> T) {
		return (List<T>) mContainerHolder.getContainer().query(T);
	}
	
	@Override
	public <T> List<T> findBySpecification(final ISpecification<T> spec) {
		return mContainerHolder.getContainer().query(new PredicatedSpecificationFor<T>(spec));
	}

	@Override
	public <T> T getBySpecification(ISpecification<T> spec) {
		List<T> allBySpec = findBySpecification(spec);
		return (allBySpec.size() == 0 ? null : allBySpec.get(0));
	}

	@Override
	public <T> void bindBySpecification(T entity, ISpecification<T> idSpec) {
		if (mContainerHolder.getContainer().ext().isStored(entity)) {
			return;
		}
		T extEntity = getBySpecification(idSpec);
		if (extEntity == null) {
			return;
		}
		long id = mContainerHolder.getContainer().ext().getID(extEntity);
		mContainerHolder.getContainer().ext().bind(entity, id);
	}

	@Override
	public <T> void delete(T entity) {
		mContainerHolder.getContainer().delete(entity);
	}

	@Override
	public <T> void save(T entity) {
		mContainerHolder.getContainer().store(entity);
	}

	public void close() {
		mContainerHolder.closeContainer();
	}
	
	@Override
	protected void finalize() throws Throwable {
		close();
		super.finalize();
	}

	@Override
	public void commit() {
		mContainerHolder.getContainer().commit();
	}
}
